import {
  addSupplier,
  deleteSupplier,
  querySupplierList,
  updateSupplier,
} from "@/services/supplier";
import {
  DrawerForm,
  ProFormList,
  ProFormText,
  ProTable,
} from "@ant-design/pro-components";
import { Button, Form, message, Popconfirm } from "antd";
import { useRef, useState } from "react";
const PurchaseOrder = () => {
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const actionRef: any = useRef(null);
  const [type, setType] = useState<string>(""); // 当前操作  编辑/新增

  // 点击编辑
  const handleEdit = (record: {
    product_name: string;
    supplier_name: string;
    id: number;
  }) => {
    setType("edit");
    const { product_name: products, supplier_name, id } = record;
    setVisible(true);
    const list = products.split(",")?.map((product_name) => ({ product_name }));
    form.setFieldsValue({
      products: list,
      supplier_name,
      id,
    });
  };

  // 点击提交
  const handleSubmit = async (values: any) => {
    console.log(values, "values");
    const { supplier_name, products, id } = values;
    const productList = products
      ?.map((item: { product_name: string }) => item.product_name)
      .join(",");
    if (!productList) {
      message.info("请添加产品后提交");
      return;
    }
    const params = {
      supplier_name,
      product_name: productList,
      id: type === "edit" ? id : undefined,
    };
    const res =
      type === "edit"
        ? await updateSupplier(params)
        : await addSupplier(params);
    if (res?.success) {
      message.success("操作成功");
      actionRef?.current?.reload();
      setVisible(false);
    } else {
      message.info(res.msg);
    }
  };

  // 删除供应商
  const handleDelSupplier = async (id: number) => {
    const res = await deleteSupplier({ id });
    if (res.success) {
      message.success("操作成功");
      actionRef?.current?.reload();
    } else {
      message.info(res.msg);
    }
  };
  // 表格列配置
  const columns = [
    {
      title: "供应商名称",
      dataIndex: "supplier_name",
      key: "supplier_name",
      width: 280,
    },
    {
      title: "包含产品",
      dataIndex: "product_name",
      key: "product_name",
      search: false,
    },
    {
      title: "操作",
      key: "action",
      width: 180,
      search: false,
      fixed: "right",
      render: (_: any, record: any) => (
        <>
          <a style={{ marginRight: 8 }} onClick={() => handleEdit(record)}>
            编辑
          </a>
          <Popconfirm
            title="提示"
            description="确定删除该供应商吗？不可恢复！"
            onConfirm={() => handleDelSupplier(record?.id)}
            okText="确定"
            cancelText="取消"
          >
            <a style={{ marginRight: 8 }}>删除</a>
          </Popconfirm>
        </>
      ),
    },
  ];

  const handleCreate = async () => {
    setType("create");
    setVisible(true);
  };

  // 请求列表
  const fetchData = async (values: any) => {
    const { current: page, pageSize: pagesize, supplier_name } = values;
    const params = {
      page,
      pagesize,
      supplier_name,
    };
    const res = await querySupplierList(params);
    return {
      data: res?.result?.data || [],
      total: res?.result?.total || 0,
      success: true,
    };
  };
  const checkUniqueName = (_, value) => {
    const products = form.getFieldValue("products") || [];
    const currentIndex = _.field.split(".")[1];
    const valuesSet = new Set();

    products.forEach((item, index) => {
      if (index !== Number(currentIndex)) {
        valuesSet.add(item?.product_name);
      }
    });

    if (valuesSet.has(value)) {
      return Promise.reject(new Error("产品名称不能重复"));
    }
    return Promise.resolve();
  };
  return (
    <>
      <ProTable
        actionRef={actionRef}
        columns={columns as any}
        request={fetchData}
        rowKey="id"
        pagination={{
          pageSize: 10,
          showSizeChanger: true,
          pageSizeOptions: ["10", "20", "50"],
        }}
        options={false}
        scroll={{ x: 1300 }}
        toolBarRender={() => [
          <Button key="add" type="primary" onClick={handleCreate}>
            新建供应商
          </Button>,
        ]}
      />
      <DrawerForm
        title={type === "edit" ? "编辑" : "新增供应商"}
        width={600}
        open={visible}
        drawerProps={{
          destroyOnClose: true,
          onClose: () => setVisible(false),
        }}
        form={form}
        onFinish={handleSubmit}
      >
        <ProFormText
          name="supplier_name"
          label="供应商名称"
          rules={[{ required: true, message: "请输入供应商名称" }]}
          placeholder="请输入供应商名称"
          width={"md"}
        />
        <ProFormText name="id" label="id" hidden />
        <ProFormList
          name="products"
          label="产品列表"
          creatorButtonProps={{
            creatorButtonText: "添加产品",
          }}
          min={0.01}
          copyIconProps={false}
          deleteIconProps={{ tooltipText: "删除" }}
          creatorRecord={{ product_name: "" }}
        >
          <ProFormText
            style={{ flex: 1 }}
            name={"product_name"}
            width="md"
            placeholder="请输入产品名称"
            rules={[
              { required: true, message: "产品名称必填" },
              { validator: checkUniqueName },
            ]}
          />
        </ProFormList>
      </DrawerForm>
    </>
  );
};

export default PurchaseOrder;
